package v1

import (
	"net/http"
	"web_framework/config"
	"web_framework/pkg/e"
	"web_framework/pkg/errno"
	"web_framework/router/api"
	"web_framework/router/middleware"
	"web_framework/service"

	"github.com/gin-gonic/gin"
)

type TrackerAPI struct {
}

func (a TrackerAPI) Name() string {
	return "tracker API"
}

func (a TrackerAPI) Bind() {
	trackerAPI := config.C.Router.Group("/api/v1/data", middleware.TrackLog())
	{
		trackerAPI.GET("p4p_tracker_login", p4pTrackerLogin)
	}
}

func p4pTrackerLogin(c *gin.Context) {
	// 检查参数是否为空
	checkList := []string{"sn", "mac", "time", "sign"}
	err, params := e.CheckEmptyParams(c, checkList)
	if err != nil {
		api.SendResponse(c, err, nil)
	}
	// 检测版本号
	sVer := c.Query("sver")
	err = e.CheckVersion(sVer)
	if err != nil {
		api.SendResponse(c, err, nil)
	}
	//签名验证   TODO p4pclient_sk待提供
	p4pclientSk := config.C.P4pclientSk
	paramsSign := []string{p4pclientSk, params["time"], params["sn"], params["mac"]}
	errSign := e.CheckSign(params["sign"], paramsSign)
	if errSign != nil {
		api.SendResponse(c, errSign, nil)
	}
	//验证SN码的合法性
	validErr := service.ValidateSN(params["sn"], params["mac"])
	if validErr != nil {
		api.SendResponse(c, errno.ErrRouterSnValidate, nil)
	}

	c.JSON(http.StatusOK, gin.H{
		"status": 1,
		"info":   "登录成功",
		"data":   nil,
	})
}
